<template>
  <el-button type="primary" v-per2="['operationsystem-list','post']" @click="doAdd">添加操作系统</el-button>
  <el-row style="margin-top:20px;">
    <el-form ref="searchFormRef" :inline="true" :model="state.searchForm">
      <el-form-item label="操作系统类型" prop="os_type">
        <el-select style="width: 160px;" v-model="state.searchForm.os_type" placeholder="系统类型" clearable>
          <el-option
              v-for="item in state.searchForm.options.os_type"
              :key="item.id"
              :label="item.label"
              :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作系统名称" prop="os_name">
        <el-input style="width: 150px;" v-model="state.searchForm.os_name" placeholder="操作系统名称" clearable/>
      </el-form-item>
      <el-form-item label="版本" prop="version">
        <el-input style="width: 100px;" v-model="state.searchForm.version" placeholder="版本" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSearch">搜 索</el-button>
        <el-button type="primary" @click="doResetSearchForm" plain>重 置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="state.tableData" border style="width: 100%" v-loading="state.isLoading"
              v-per2="['operationsystem-list','get']">
      <el-table-column type="selection" width="55" label="选择"/>
      <el-table-column label="序号">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="os_type_text" label="操作系统类型"/>
      <el-table-column sortable prop="os_name" label="操作系统名称"/>
      <el-table-column sortable prop="os_abbr" label="操作系统英文名称"/>
      <el-table-column sortable prop="version" label="操作系统版本"/>
      <el-table-column
          v-if="hasButton([{name:'operationsystem-detail',method:'put'},{name:'operationsystem-detail',method:'delete'}])"
          label="操作">
        <template #default="scope">
          <el-popconfirm

              cancel-button-type="danger"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmDelete(scope.row)"
              title="确认删除吗?">
            <template #reference>
              <el-button v-per2="['operationsystem-detail','delete']" type="danger" size="small" icon="Delete"
                         class="card-small-btn">删 除
              </el-button>
            </template>
          </el-popconfirm>
          <el-button v-per2="['operationsystem-detail','put']" type="success" size="small" icon="Edit"
                     class="card-small-btn"
                     @click="doEdit(scope.row,scope.$index)">编 辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <MinePager v-per2="['operationsystem-list','get']" :pager="state.pager"/>
  </el-row>
  <MineDialog :obj="state.dialog" ref="formRef"/>

</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import _axios from "@/plugin/axios.js";
import {ElMessage} from "element-plus";
import MineDialog from "@/components/DialogSingle.vue";
import MinePager from "@/components/MinePager.vue";
import {hasButton, hasPermission2} from "@/stores/permission.js";
import {clearFormError} from "@/plugin/form.js";


const searchFormRef = ref(null)
const formRef = ref()
const state = reactive({
  isLoading: false,
  tableData: [],
  pager: {
    currentPage: 1,
    totalCount: 0,
    perPageSize: 10,
    handleSizeChange: handleSizeChange,
    handleChangePage: handleChangePage
  },
  editId: -1,
  editIndex: -1,
  dialog: {
    visible: false,
    title: "",
    form: {
      os_type: 2,
      os_name: "",
      os_abbr: "",
      version: "",
    },
    options: {
      os_type: [
        {id: 1, title: "Windows"},
        {id: 2, title: "Linux"},
      ]
    },
    errors: {
      os_type: "",
      os_name: "",
      version: "",
      os_abbr: "",
    },
    fields: [
      {name: 'os_type', label: '操作系统类型', wiget: 'radio'},
      {name: 'os_name', label: '操作系统名称', wiget: 'input'},
      {name: 'os_abbr', label: '操作系统英文名称', wiget: 'input'},
      {name: 'version', label: '操作系统版本', wiget: 'input'},
    ],
    rules: {
      os_type: [
        {required: true, message: '请选择操作系统类型', trigger: 'blur'},
      ],
      os_name: [
        {required: true, message: '请输入操作系统名称', trigger: 'blur'},
      ],
      os_abbr: [
        {required: true, message: '请输入操作系统英文名称', trigger: 'blur'},
      ],
      version: [
        {required: true, message: '请输入操作系统版本', trigger: 'blur'},
      ]
    },
    doSubmit: doSubmit
  },
  searchForm: {
    os_type: "",
    os_name: "",
    version: "",
    options: {
      os_type: [
        {id: 1, label: "Windows"},
        {id: 2, label: "Linux"}
      ]
    }
  }
})


onMounted(() => {
  initTableData()
})

function doResetSearchForm() {
  searchFormRef.value.resetFields()
}

function doSearch() {
  state.pager.currentPage = 1
  initTableData()
}

function initTableData() {
  if (hasPermission2("operationsystem-list", "get")) {
    let search_params = {page: state.pager.currentPage, page_size: state.pager.perPageSize}
    for (let key in state.searchForm) {
      let value = state.searchForm[key]
      search_params[key] = value
    }
    _axios.get("/api/web/operation_system/", {params: search_params}).then((res) => {
      if (res.data.code === 0) {
        state.tableData = res.data.data.data;
        state.pager.totalCount = res.data.data.totalCount;
        state.pager.perPageSize = res.data.data.perPageSize
      }
    })
  }
}


function handleChangePage(page) {
  state.pager.currentPage = page
  initTableData()
}

function handleSizeChange(page_size) {
  state.pager.perPageSize = page_size
  state.pager.currentPage = 1
  initTableData()
}

function doAdd() {
  state.dialog.visible = true
  state.dialog.title = "添加操作系统"
  state.editId = -1
  state.editIndex = -1
  clearFormError(state.dialog.errors)
  state.dialog.form = {
    os_type: 1,
    os_name: "",
    os_abbr:"",
    version: ""
  }
}

function doEdit(row, index) {
  clearFormError(state.dialog.errors)
  state.dialog.visible = true
  state.dialog.title = '编辑操作系统'
  state.editId = row.id
  state.editIndex = index
  let dict = state.tableData[index]
  state.dialog.form = {
    os_type: dict.os_type,
    os_name: dict.os_name,
    os_abbr: dict.os_abbr,
    version: dict.version,
  }
}

function confirmDelete(row) {
  _axios.delete(`/api/web/operation_system/${row.id}/`).then((res) => {
    if (res.data.code === 0) {
      state.tableData = state.tableData.filter((item) => {
        return row.id !== item.id
      })
      ElMessage.success("删除成功")
    } else {
      ElMessage.error("删除失败")
    }
  })
}

function doSubmit() {
  formRef.value.ruleForm.validate((valid, fields) => {
    if (valid) {
      if (state.editId > 0) {
        _axios.patch(`/api/web/operation_system/${state.editId}/`, state.dialog.form).then((res) => {
          if (res.data.code === 0) {
            state.tableData[state.editIndex] = res.data.data
            state.editId = -1
            state.editIndex = -1
            state.dialog.visible = false
          } else if (res.data.code === 2001) {
            for (let key in res.data.detail) {
              state.dialog.errors[key] = res.data.detail[key][0]
            }
          } else {
            ElMessage.error("编辑失败")
          }
        })
      } else {
        state.dialog.errors = {}
        _axios.post('/api/web/operation_system/', state.dialog.form).then((res) => {
          if (res.data.code === 0) {
            //state.tableData.unshift(res.data.data)
            state.dialog.visible = false
            initTableData()
          } else if (res.data.code === 2001) {
            for (let key in res.data.detail) {
              state.dialog.errors[key] = res.data.detail[key][0]
            }
          } else {
            ElMessage.error("添加失败")
          }
        })
      }
    }
  })
}


</script>

<style scoped>

</style>